import React from 'react';
import style from './style.styl';
import cx from 'classnames';
import ReviewHeader from '../review/new/tool/ReviewHeader';
import { Input,DateSelect,success } from '../../ui-components'; 
import moment from 'moment';
import {Button, Link, Avatar} from 'sq-ui';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import * as conversationActions from '../../actions/conversation.action'
import ConverCell from './plugins/ConverCell';
import ConverTable from './plugins/ConverTable';
import util from '../../util';
import RecordModal from './RecordModal';

const pageSize = 4;

@connect(({ app,conversation }) => ({ app,conversation }), dispatch => ({actions: bindActionCreators({...conversationActions}, dispatch)}))
class ConversationRecords extends React.Component {
  static contextTypes = {
    router: React.PropTypes.object
  }
  constructor(props) {
    super(props);
    this.displayName = 'ConversationRecords';
    this.state={
      user: {},
      showModal: false,
      recordItem: {},
    }
  }
  componentWillMount() {
    if(this.props.byUser) return;
    const {
      user
    } = this.props.location.state || {};
    if(user){
      this.setState({
        user: user,
      });
    }else {
      this.props.actions.getSchedule(this.props.params.itemId, (res) => {
        this.setState({
          user: (res.data|| {}).targetUserProfile,
        })
      });
    }
  }
  componentDidMount() {
    this.onFetchRecord();
  }
  componentWillUnmount() {
    this.props.actions.clearSchedule(); 
  }
  componentWillReceiveProps(nextProps) {
    const pageNum = this.getPageNum(this.props);
    const nextPageNum = this.getPageNum(nextProps);
    if(pageNum !== nextPageNum) {
      this.onFetchRecord(nextPageNum);
    }
  }
  getPageNum = (props) => {
    const {
      pageNum = 1,
    } = props.location.query;
    return pageNum;
  }
  onFetchRecord = (pageNum) => {
    const pageNumber = pageNum || this.getPageNum(this.props);
    const {
      byUser
    } = this.props;
    if(byUser){
      this.props.actions.fetchRecordByUser({
        pageNumber: pageNumber,
        pageSize: pageSize
      }); 
    }else {
      const itemId = this.props.params.itemId;
      this.props.actions.fetchRecord(itemId, {
        pageNumber: pageNumber,
        pageSize: pageSize
      }); 
    }
    
  }
  goBack = () => {
    const {
      pageNum = 1,
    } = this.props.location.state || {};
    this.context.router.push({
      pathname: '/conversation/initiate',
      query: {
        pageNum: pageNum,
      }
    })
  }
  toggleModal = (flag, recordItem) => {
    this.setState({
      showModal: flag,
      recordItem: recordItem || {},
    })
  }
  showRecord = (id) => {
    this.props.actions.getRecord(id, (res) => {
      this.toggleModal(true, res.data);
    })
  }
  handleSubmit = (id, data) => {
    this.props.actions.updateRecord(id, data, () => {
      success('修改成功');
      this.onFetchRecord();
    });
  }
  onPage = (pageNum) => {
    this.context.router.push({
      pathname: this.props.location.pathname,
      query: {
        pageNum: pageNum,
      }
    })
  }
  render() {
    const {
      records
    } = this.props.conversation;
    const pageNumber = this.getPageNum(this.props);
    const recordsData = {
      pageNum: pageNumber,
      pageCount: 0,
      data: null,
    };
    let userProfileVOs = [];
    if(records[`page_${pageNumber}`]){
      const dataItem = records[`page_${pageNumber}`];
      const {
        totalNumber = 0,
        convrRecordVOs = [],
      } = dataItem || {};
      recordsData.pageCount = Math.ceil(totalNumber/pageSize);
      recordsData.data = convrRecordVOs || [];
      userProfileVOs = dataItem.userProfileVOs || [];
    }
    const {
      byUser
    } = this.props;
    return (
      <div>
        {
          byUser ? null :
          <ReviewHeader title={`与${this.state.user.fullName}的交谈`} goBack={this.goBack}  />
        }
        <ConverTable data={recordsData} fetchData={this.onPage} >
          <ConverCell item={v => v.sourceUserId} header={'发起人'} width={300} render={v => {
            const item = userProfileVOs.find(u => u.userId === v) || {};
            return (
              <Link to={`/okr/objective-targetAll?userId=${item.userId}`}>
                <span className={style['user-span']}>
                  <Avatar src={item.avatarUrl} width={36}/>
                  <span>{item.fullName}</span>
                </span>
              </Link>
            );
          }}/>
          <ConverCell item={v => v['convrDate']} header={'沟通时间'} render={v => util.dateFormat(new Date(+v), 'yyyy-MM-dd')} />
          <ConverCell item={v => v} header={'操作'} render={v => {
            return <Button className={style['cell-btn']} radius={'15px'} style={{height: '30px'}} blueLine label={'查看详情'} onClick={this.showRecord.bind(this, v.convrRecordId)} />
          }} />
        </ConverTable>
        <RecordModal 
          handleSubmit={this.handleSubmit} 
          sourceId={(this.props.app.profile||{}).userId} 
          recordItem={this.state.recordItem} 
          showModal={this.state.showModal} 
          toggleModal={this.toggleModal}
        />
      </div>
    );
  }
}

export default ConversationRecords;